package websocket

import (
	"fmt"
	"log"
	"sync"
)

var (
	// 全局WebSocket服务器实例
	globalServer *WebSocketServer
	serverMux    sync.RWMutex
)

// InitWebSocketServer 初始化WebSocket服务器
func InitWebSocketServer() error {
	serverMux.Lock()
	defer serverMux.Unlock()
	
	if globalServer != nil {
		return fmt.Errorf("WebSocket服务器已经初始化")
	}
	
	globalServer = NewWebSocketServer()
	log.Println("WebSocket服务器初始化成功")
	
	return nil
}

// StartWebSocketServer 启动WebSocket服务器
func StartWebSocketServer(port string) error {
	serverMux.RLock()
	server := globalServer
	serverMux.RUnlock()
	
	if server == nil {
		return fmt.Errorf("WebSocket服务器未初始化")
	}
	
	log.Printf("启动WebSocket服务器在端口: %s", port)
	
	// 在新的goroutine中启动服务器，避免阻塞
	go func() {
		if err := server.Start(port); err != nil {
			log.Printf("WebSocket服务器启动失败: %v", err)
		}
	}()
	
	return nil
}

// StopWebSocketServer 停止WebSocket服务器
func StopWebSocketServer() {
	serverMux.Lock()
	defer serverMux.Unlock()
	
	if globalServer != nil {
		globalServer.Stop()
		globalServer = nil
		log.Println("WebSocket服务器已停止")
	}
}

// GetWebSocketServer 获取WebSocket服务器实例
func GetWebSocketServer() *WebSocketServer {
	serverMux.RLock()
	defer serverMux.RUnlock()
	return globalServer
}

// BroadcastMessage 广播消息给所有连接的客户端
func BroadcastMessage(message interface{}) error {
	serverMux.RLock()
	server := globalServer
	serverMux.RUnlock()
	
	if server == nil {
		return fmt.Errorf("WebSocket服务器未初始化")
	}
	
	server.Broadcast(message)
	return nil
}

// GetConnectedClientsCount 获取连接的客户端数量
func GetConnectedClientsCount() int {
	serverMux.RLock()
	server := globalServer
	serverMux.RUnlock()
	
	if server == nil {
		return 0
	}
	
	return server.GetConnectedClients()
}

// IsServerRunning 检查服务器是否正在运行
func IsServerRunning() bool {
	serverMux.RLock()
	defer serverMux.RUnlock()
	return globalServer != nil
}

// SendNotification 发送通知消息
func SendNotification(title, message string, data interface{}) error {
	notification := Response{
		Type:    "notification",
		Success: true,
		Message: message,
		Data: map[string]interface{}{
			"title": title,
			"data":  data,
		},
	}
	
	return BroadcastMessage(notification)
}

// SendSystemMessage 发送系统消息
func SendSystemMessage(message string) error {
	systemMsg := Response{
		Type:    "system",
		Success: true,
		Message: message,
	}
	
	return BroadcastMessage(systemMsg)
}

// Cleanup 清理WebSocket资源
func Cleanup() {
	StopWebSocketServer()
}